importClass(android.content.Context);
importClass(android.content.pm.PackageManager);

let helperFun = {
    fileName: "videoData"
};

helperFun.appPkgName = 'com.smile.gifmaker'

/**
 * 把JS对象转成json字符串打印
 * @param info: 任意类型数据
 * @return undefined
 */
helperFun.logStringify = function (info){
    logd(JSON.stringify(info));
}
/**
 * @description 返回并等待
 * @param count {number?} 返回次数,默认1次
 * @param delay {number?} 延迟毫秒数,默认1000
 */

helperFun.backs =(count, delay) => {
    count = count || 1;
    delay = delay || 1000;
    for (let i = 0; i < count; i++) {back();sleep(delay)}
}

/**
 * @description 返回主页
 * @param count {number?} 返回次数,默认1次
 * @param delay {number?} 延迟毫秒数,默认1000
 */

helperFun.homes =(count, delay) => {
    count = count || 1;
    delay = delay || 1000;
    for (let i = 0; i < count; i++) {home();sleep(delay)}
}

/**
 * 用于获取EC版本号
 * @return 返回一个数组格式的版本号 方便做比较 如: [7,2,0] 对应的 7.2.0
 */
helperFun.getECversion = function (){
    return acEvent.version().split('.').map(Number);
}

/**
 * Params:
 *  startX – 起始坐标的X轴值
 *  startY – 起始坐标的Y轴值
 *  endX – 结束坐标的X轴值
 *  endY – 结束坐标的Y轴值
 *  delay – 持续时长 单位毫
 * @return true 滑动成功, false 滑动失败
 */
helperFun.randomSwiper = function (startX, startY, endX, endY, delay) {
    delay = delay || 200
    let randomNum = random(1, 30);
    return swipeToPoint(startX + randomNum, startY + randomNum, endX + randomNum, endY + randomNum,delay)
}

/**
 *
 * params: 为任何类型的数据
 * return: 指定JS类型数据 如Object Array String Number等
 * */
helperFun.getType = function (obj){
    const type = Object.prototype.toString.call(obj);
    return type.slice(8, -1);
}
/**
 * 功能 判断一个js对象是否是空对象
 * params: 为任何类型的数据
 * return: Boolean类型
 * */
helperFun.isEmptyObject = function (obj) {
    if (typeof obj !== 'object') {
        return false;
    }
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            return false;
        }
    }
    return true;
}

/**
 * Params:
 *  msg – 气泡提示的信息内容
 *  min – 最小随机范围(秒)
 *  max – 最大随机范围(秒)
 * @return true 滑动成功, false 滑动失败
 */
helperFun.showToast = function (msg, min, max) {
    min = min || 1;
    max = max || 3;
    sleep(random(min,max) * 1000);
    toast(msg + "等待完成!");
}

// 通过数组中对象的videoName
helperFun.findTabByName = (tabs,timeName) => {
    if (helperFun.getType(tabs) === 'Array') {
        // return tabs.find(tab => tab.videoName === name); 有个坑
        // return tabs.find(tab => name.includes(tab.videoName));
        // let leftText = name.split("#")[0].slice(0,-2); // 这里时不时会出现搜索图标 时有时无 这种方式摒弃丢了!!!
        // let rightText = name.split("#")[1];
        return tabs.find(tab => tab.videoTime.includes(timeName));
    } else {
        logd('类型错误:' + helperFun.getType(tabs))
    }
}

// 通过数组中对象的index
helperFun.findTabByIndex = (tabs, index) => {
    if (helperFun.getType(tabs) === 'Array') {
        return tabs.find(tab => tab.index === index);
    } else {
        logd('类型错误:' + helperFun.getType(tabs))
    }
}

helperFun.updateGatherByName = (tabs, name, gather) => {
    tabs.find(item => item.videoName === name).gather = gather;
    return tabs.map(item => item)
}

/**
 * @description 包名是否在前台
 * @param pkgName{string} 包名
 * @return {boolean} true/false
 */
helperFun.isRunningPkg = function (pkgName) {
    pkgName = pkgName || helperFun.appPkgName;
    return !!pkg(pkgName).getOneNodeInfo(0);
};

/**
 * @description 检测应用是否在前台 如果不在那么就自动启动应用
 * @param pkgName{string} 包名
 * @return {boolean} true/false
 */
helperFun.checkAppStatus = function () {
    let i = 0;
    do {
        if (helperFun.isRunningPkg()) {return true}// 如果已经在前台那么直接返回
        // 启动应用
        utils.openApp(helperFun.appPkgName)
        i++;
        sleep(1000);
    } while (i < 5);

}
// 匹配字符中的数字
helperFun.matchNumber = function (str) {
    if(!str) return -1;
    str = str.match(/\d+/);
    if (Array.isArray(str)) {return +str[0];}
}
/*
* 功能:获取节点通用方式
* params:
*   selector: 选择器
* */
helperFun.getNode = function (selector) {
    if (!selector) return false; // 如果传入参数为false/null/0/""/undefined 直接返回false

    if (selector.constructor.name !== "S") {
        helperFun.logStringify("参数类型不对:" + JSON.stringify(selector));
        return false;
    }

    let nodeInfo = selector.getOneNodeInfo(1); // 获取当前传入的选择器的节点信息

    if (!nodeInfo) { // 获取失败返回
        // helperFun.logStringify('未找到 可能不在当前页面' + JSON.stringify(selector));
        return false;
    }
    // helperFun.logStringify(nodeInfo)
    return nodeInfo;
}

// 获取时分秒
helperFun.getSystemTime = () => {
    const padZero = (num) => {
        return num < 10 ? "0" + num : num;
    }
    const date = new Date();
    const hour = padZero(date.getHours());
    const minute = padZero(date.getMinutes());
    const second = padZero(date.getSeconds());
    return hour + ":" + minute + ":" + second
}

//判断一个数组是否为空数组
helperFun.isEmptyArray = (arr) => {
    return Array.isArray(arr) && arr.length === 0;
}

// 用于倒计时效果
helperFun.countDown = (seconds, callback) => {
    let flag = true;

    for (let i = 0; i < seconds; i++) {
        if (!flag) break;
        if (i >= seconds || (typeof callback === "function" && callback())) {
            toast("倒计时结束!");
            break;
        } else {
            toast("倒计时剩余时间:" + (seconds - i) + "秒");
        }
        sleep(1000);
    }

    return function () {
        flag = false;
        console.log("倒计时已提前退出");
    };
}

helperFun.getTimestamp = () => {
    const currentDate = new Date();
    return currentDate.getTime();
}

helperFun.formatTime = (duration) => {
    const minutes = Math.floor(duration / 60000);
    const seconds = ((duration % 60000) / 1000).toFixed(0);
    return (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
}

helperFun.formatSecondsTime = (seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return (minutes < 10 ? '0' : '') + minutes + ':' + (remainingSeconds < 10 ? '0' : '') + remainingSeconds;
}

// 用于提示用户时间
helperFun.tipUserTime = (obj, count) => {
    let timestamp = helperFun.getTimestamp();
    let msg = "本轮还剩余:" + helperFun.formatTime(obj.endTimestamp - timestamp) + "后 进入休息模式!";
    count % 5 === 0 && toast(msg);
    return timestamp
}

/**
 * @description 保存内容至文件中 注: .json为后缀
 * @return 无
 */

helperFun.saveConfigJsonFile = (obj) => {
    if (helperFun.getType(obj) !== 'Object' && helperFun.getType(obj) !== 'Array') {logd('保存时必须 类型出错: 必须为js对象'); return }
    let path = "/sdcard/" + helperFun.fileName + ".json";

    if (!file.exists(path)) {
        // logd('文件不存在');
        file.create(path)
    }
    file.writeFile(JSON.stringify(obj), path);
}

/**
 * @description 删除文件 注: .json为后缀
 * @return 读取返回的json数据
 */

helperFun.readConfigJsonFile = () => {
    let path = "/sdcard/" + helperFun.fileName + ".json";
    return file.readFile(path);
}


/**
 * @description 删除文件 注: .json为后缀
 * @return 无
 */
helperFun.deleteConfigJsonFile = () => {
    let path = "/sdcard/" + helperFun.fileName + ".json";
    file.deleteAllFile(path);
}

// 导出utils对象
module.exports = helperFun;